<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
    <style>
        /* 页面整体样式 */
        body {
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #fff3e0; /* 浅橙色背景 */
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        /* 导航栏样式 */
        .navbar {
            background-color: #FF324A; /* 橙色背景 */
            padding: 10px 20px;
            display: flex;
            justify-content: flex-start; /* 将导航栏内容左对齐 */
            align-items: center;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            width: 100%;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
        }

        .nav-link {
            color: #ffffff;
            text-decoration: none;
            font-size: 18px;
            font-weight: bold;
            padding: 10px 20px;
            border-radius: 5px;
            transition: background-color 0.3s ease, color 0.3s ease;
        }

        .nav-link:hover {
            background-color: #D7372B; /* 更深的蓝色 */
            color: #ffffff;
        }

        .nav-link:active {
            background-color: #FF0036;
        }

        /* 主内容区域样式 */
        .content {
            display: flex;
            width: 90%;
            max-width: 1200px;
            margin-top: 100px; /* 确保内容不被导航栏覆盖 */
        }

        /* 商品展示样式 */
        .product-list {
            flex: 2;
            margin-right: 20px;
        }

        .product {
            border: 1px solid #90caf9; /* 蓝色边框 */
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
            transition: transform 0.3s ease;
        }

        .product:hover {
            transform: translateY(-5px);
        }

        .product img {
            max-width: 100%;
            height: auto;
            border-radius: 8px;
        }

        .product h3 {
            margin: 15px 0;
            font-size: 1.5em;
            color: #333;
        }

        .product p {
            margin: 5px 0;
            color: #555;
        }

        .product svg {
            width: 16px; /* 调整图标大小 */
            height: 16px;
            vertical-align: middle;
            margin-right: 5px;
        }

        /* 购物心得样式 */
        .reviews {
            position: fixed;
            right: 20px;
            top: 120px;
            width: 320px;
            background-color: #C68642;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            max-height: 500px;
            overflow-y: auto; /* 添加垂直滚动条 */
            border: 1px solid #ddd;
        }

        #reviewContainer {
            position: relative;
            animation: scrollReviews 10s linear infinite; /* 添加滚动动画 */
        }

        @keyframes scrollReviews {
            0% { top: 0; }
            100% { top: -100%; } /* 根据内容调整滚动距离 */
        }

        .review {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
            transition: transform 0.3s ease;
            text-align: center; /* 文字居中 */
            background-color: #FFE8D6; /* 更改卡片颜色为浅绿色 */
        }

        .review:hover {
            transform: translateY(-3px);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .review p {
            margin: 8px 0;
            color: #444;
            font-size: 1.1em; /* 增加字体大小 */
        }

        .review strong {
            color: #222;
        }

        /* 分页控件样式 */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 20px;
        }

        .pagination button {
            background-color: #1e88e5; /* 深蓝色按钮 */
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 20px;
            cursor: pointer;
            margin: 0 5px;
            transition: background-color 0.3s ease, transform 0.3s ease;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }

        .pagination button:hover {
            background-color: #1565c0;
            transform: translateY(-2px);
        }

        .pagination span {
            font-size: 16px;
            color: #555;
        }

        .nav-right {
            margin-left: 20px; /* 调整左边距以向左移动 */
        }

        .sell-product-btn {
            background-color: transparent;
            border: none;
            color: #ffffff;
            font-size: 18px;
            font-weight: bold;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease, color 0.3s ease;
        }

        .sell-product-btn:hover {
            background-color: #FF324A;
        }

        .sell-product-btn:active {
            background-color: #0d47a1;
        }

        .add-to-cart-btn {
            background-color: #FF0036;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
            margin-top: 10px;
            transition: background-color 0.3s ease;
        }

        .add-to-cart-btn:hover {
            background-color: #1565c0;
        }

        .reviews h3 {
            text-align: center; /* 标题居中 */
            font-size: 1.5em; /* 增大字体 */
            margin-bottom: 20px;
        }

        .pagination button {
            padding: 5px 10px; /* 缩小按钮大小 */
            font-size: 14px; /* 调整字体大小 */
        }

        /* 广播容器样式 */
        .broadcast {
            width: 100%;
            background-color: #FFE8D6; /* 黄色背景 */
            color: #333;
            padding: 10px 0;
            overflow: hidden;
            white-space: nowrap;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            position: fixed;
            top: 60px;
            z-index: 999;
        }

        .broadcast-content {
            display: inline-block;
            padding-left: 100%;
            animation: scrollBroadcast 40s linear infinite;
        }

        @keyframes scrollBroadcast {
            0% { transform: translateX(0); }
            100% { transform: translateX(-100%); }
        }

        /* 美化后的模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 1000;
            background-color: #f9f9f9;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
            width: 90%;
            max-width: 500px;
        }

        .modal-content {
            position: relative;
        }

        .close {
            position: absolute;
            top: 15px;
            right: 15px;
            cursor: pointer;
            font-size: 24px;
            color: #333;
        }

        .modal h2 {
            margin-top: 0;
            color: #333;
            text-align: center;
        }

        .modal form {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .modal input {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }

        .modal button {
            padding: 10px;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .modal button[type="button"] {
            background-color: #3498db;
            color: white;
        }

        .modal button[type="button"]:hover {
            background-color: #2980b9;
        }

        .modal button[type="button"]:last-child {
            background-color: #e74c3c;
        }

        .modal button[type="button"]:last-child:hover {
            background-color: #c0392b;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <div class="navbar">
        <div class="nav-left">
            <a href="index.jsp" class="nav-link">首页</a>
            <a href="car.jsp" class="nav-link">购物车</a>
            <a href="getOrders" class="nav-link">查看订单</a>
            <button class="sell-product-btn">售卖商品</button>
        </div>
        <div class="nav-right">
            <% 
                String username = (String) session.getAttribute("username");
                if (username != null) { 
            %>
                <span class="nav-link">欢迎, <%= username %></span>
                <a href="logout" class="nav-link">退出</a>
            <% 
                } else { 
            %>
                <a href="login.jsp" class="nav-link">登录</a>
            <% 
                } 
            %>
        </div>
    </div>

    <!-- 广播容器 -->
    <div class="broadcast">
        <div class="broadcast-content" id="broadcastContent">
            <!-- 用户评价将通过JavaScript动态加载 -->
        </div>
    </div>

    <!-- 主内容区域 -->
    <div class="content">
        <!-- 商品展示 -->
        <div class="product-list" id="productList">
            <!-- 商品内容将通过JavaScript动态加载 -->
        </div>

        <!-- 购物心得 -->
        <div class="reviews">
            <h3>购物心得</h3>
            <div id="reviewContainer">
                <!-- 购物心得内容将通过JavaScript动态加载 -->
            </div>
            <div class="pagination">
                <button id="prevReviewPage" onclick="changeReviewPage(-1)">上一页</button>
                <span id="reviewPageInfo"></span>
                <button id="nextReviewPage" onclick="changeReviewPage(1)">下一页</button>
            </div>
        </div>
    </div>

    <div class="pagination">
        <button id="prevPage" onclick="changePage(-1)">上一页</button>
        <span id="pageInfo"></span>
        <button id="nextPage" onclick="changePage(1)">下一页</button>
    </div>

    <!-- 添加商品模态框 -->
    <div id="addShopModal" class="modal" style="display:none;">
        <div class="modal-content">
            <span class="close" onclick="closeModal('addShopModal')">&times;</span>
            <h2>添加商品</h2>
            <form id="addShopForm">
                <input type="text" id="shopName" name="shopName" placeholder="商品名称" required>
                <input type="text" id="imageUrl" name="imageUrl" placeholder="图片地址" required>
                <input type="number" id="shopPrice" name="shopPrice" placeholder="价格" step="0.01" required>
                <input type="text" id="shopContactPerson" name="shopContactPerson" placeholder="联系人" required>
                <input type="text" id="shopContactPhone" name="shopContactPhone" placeholder="联系电话" required>
                <button type="button" onclick="submitAddShop()">添加</button>
                <button type="button" onclick="closeModal('addShopModal')">取消</button>
            </form>
        </div>
    </div>

    <script>
        window.onload = function() {
            document.querySelector('.sell-product-btn').addEventListener('click', showAddShopModal);
            loadProducts();
            loadReviews();
            loadBroadcastReviews();
        };
        let currentPage = 1;
        const pageSize = 5;
        let totalShops = 0;

        function loadProducts() {
            fetch(`/untitled_war_exploded/getShops?page=${currentPage}`)
                .then(response => response.json())
                .then(data => {
                    totalShops = data.totalShops;
                    renderProducts(data.shops);
                    updatePagination();
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取商品信息失败');
                });
        }

        function changePage(direction) {
            currentPage += direction;
            loadProducts();
        }

        function updatePagination() {
            const totalPages = Math.ceil(totalShops / pageSize);
            document.getElementById('pageInfo').textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
            document.getElementById('prevPage').disabled = currentPage === 1;
            document.getElementById('nextPage').disabled = currentPage >= totalPages;
        }

        // JavaScript for pagination in reviews
        let currentReviewPage = 1;
        const reviewPageSize = 5;

        function loadReviews() {
            fetch(`/untitled_war_exploded/getMarks?page=${currentReviewPage}`)
                .then(response => response.json())
                .then(data => {
                    const reviewContainer = document.getElementById('reviewContainer');
                    reviewContainer.innerHTML = '';
                    data.forEach(mark => {
                        const reviewElement = document.createElement('div');
                        reviewElement.classList.add('review');
                        reviewElement.innerHTML = `
                            <p><strong>用户：</strong>${mark.userId}</p>
                            <p><strong>内容：</strong>${mark.content}</p>
                        `;
                        reviewContainer.appendChild(reviewElement);
                    });
                    updateReviewPagination();
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取评价信息失败');
                });
        }

        function changeReviewPage(direction) {
            currentReviewPage += direction;
            loadReviews();
        }

        function updateReviewPagination() {
            const totalReviewPages = Math.ceil(document.querySelectorAll('.review').length / reviewPageSize);
            document.getElementById('reviewPageInfo').textContent = `第 ${currentReviewPage} 页，共 ${totalReviewPages} 页`;
            document.getElementById('prevReviewPage').disabled = currentReviewPage === 1;
            document.getElementById('nextReviewPage').disabled = currentReviewPage >= totalReviewPages;
        }

        function loadBroadcastReviews() {
            fetch(`/untitled_war_exploded/getMarks?page=1`)
                .then(response => response.json())
                .then(data => {
                    const broadcastContent = document.getElementById('broadcastContent');
                    broadcastContent.innerHTML = '';
                    data.forEach(mark => {
                        broadcastContent.innerHTML += `<span style="margin-right: 50px;">${mark.content}</span>`;
                    });
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }

        // 渲染商品信息
        function renderProducts(shops) {
            const productList = document.getElementById('productList');
            productList.innerHTML = ''; // 清空当前内容

            shops.forEach(shop => {
                const productHtml = `
                    <div class="product">
                        <img src="${shop.url}" alt="${shop.name}">
                        <h3>商品名称：${shop.name}</h3>
                        <p class="price">价格：${shop.price}</p>
                        <p class="contact"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>联系人：${shop.contactPerson}</p>
                        <p class="contact"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"/></svg>联系电话：${shop.contactPhone}</p>
                        <button class="add-to-cart-btn" onclick="addToCart('${shop.id}')">添加至购物车</button>
                    </div>
                `;
                productList.innerHTML += productHtml;
            });
        }

        function addToCart(productId) {
            fetch(`/untitled_war_exploded/addToCar?shopId=${productId}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('商品已添加至购物车');
                } else {
                    alert('添加至购物车失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('添加至购物车失败');
            });
        }

        // 检查用户是否已登录
        const isLoggedIn = <%= session.getAttribute("loggedIn") != null ? "true" : "false" %>;

        // 显示模态框或重定向到登录页面
        function showAddShopModal() {
            if (!isLoggedIn) {
                window.location.href = 'login.jsp';
                return;
            }
            document.getElementById('addShopModal').style.display = 'block';
        }

        // 关闭模态框
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        // 提交新增商品表单
        function submitAddShop() {
            console.log("submitAddShop");
            const shopName = document.getElementById('shopName').value;
            const imageUrl = document.getElementById('imageUrl').value;
            const shopPrice = document.getElementById('shopPrice').value;
            const shopContactPerson = document.getElementById('shopContactPerson').value;
            const shopContactPhone = document.getElementById('shopContactPhone').value;
            const url = new URL('/untitled_war_exploded/addShop', window.location.origin);
            url.searchParams.append('shopName', shopName);
            url.searchParams.append('imageUrl', imageUrl);
            url.searchParams.append('shopPrice', shopPrice);
            url.searchParams.append('shopContactPerson', shopContactPerson);
            url.searchParams.append('shopContactPhone', shopContactPhone);

            fetch(url, {
                method: 'POST'
            })
            .then(response => response.text())
            .then(data => {
                alert(data);
                closeModal('addShopModal');
            })
            .catch(error => {
                console.error('Error:', error);
                alert('添加商品失败');
            });
        }

        // 更新售卖商品按钮的点击事件
        document.querySelector('.sell-product-btn').addEventListener('click', showAddShopModal);
    </script>
</body>
</html>